<?php

namespace App\Http\Controllers\Client;

use App\Validate;
use Redis;
use App\Http\Middleware\User;
use App\Users;
use Illuminate\Routing\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use iscms\AlismsSdk\AlibabaAliqinFcSmsNumSendRequest;
use iscms\AlismsSdk\TopClient;
use Mews\Captcha\Facades\Captcha;

use App\Ad;

class LoginController extends Controller
{
    //载入登录页
    public function index()
    {
        $ad4 = Ad::where('id',4)->first();
        $ad5 = Ad::where('id',5)->first();
        $ad6 = Ad::where('id',6)->first();
        return view('client.login',['ad4'=>$ad4,'ad5'=>$ad5,'ad6'=>$ad6]);
    }

    //生成验证码
    public function captcha()
    {
        return Captcha::create('default');
    }

    //载入注册页
    public function toRegister()
    {
        $ad4 = Ad::where('id',4)->first();
        $ad5 = Ad::where('id',5)->first();
        $ad6 = Ad::where('id',6)->first();
        return view('client.register',['ad4'=>$ad4,'ad5'=>$ad5,'ad6'=>$ad6]);
    }

    //生成注册手机验证码
    public function registerPhone()
    {
        $obj = new Users;
        //验证手机号是否合法
        $validate = $obj->phoneValidate(input::all());
        if ($validate->fails()) {
            echo json_encode(array('code' => 17, 'msg' => '手机不合法'));
            exit();
        }
        $phone = input::get('phone');
        $c = new TopClient();
        //创建随机数
        $num = rand(100000, 999999); //组装参数
        //生成json串
        $p = [
            'number' => "$num",
        ];
        $pp = json_encode($p);
        //获取密钥
        $c->appkey = config('alisms.KEY');
        $c->secretKey = config('alisms.SECRETKEY');
        //设置参数
        $req = new AlibabaAliqinFcSmsNumSendRequest();
        $req->setSmsType('normal');
        $req->setSmsParam($pp);
        $req->setSmsFreeSignName('保祥云商城');
        $req->setRecNum($phone);
        $req->setSmsTemplateCode('SMS_35320065');
        $rsp = $c->execute($req);
        $vali = Validate::where('phone', $phone)->first();
        if ($vali) {
            Validate::where('phone', $phone)->update(['code' => $num]);
        } else {
            Validate::insert([
                'code' => $num,
                'phone' => $phone
            ]);
        }
        echo $rsp = json_encode($rsp, JSON_UNESCAPED_UNICODE);
    }

    //注册新用户
    public function register()
    {
        $car_num = input::get('car_num');
        $phone = input::get('phone');
        $password = md5(input::get('password'));
        $d_password = md5(input::get('password_confirmation'));
        $code = input::get('code');
        $v = Validate::where('phone', $phone)->first();
        if ($v && time() - strtotime($v->create_time) < 300 && $code == $v->code) {
            if ($password != $d_password) {
                return redirect()->back()->withInput()->withErrors('两次密码不一致，请重新输入!');
            }
            $list = Users::where('car_num',$car_num)->first();
            if (!empty($list)) {
                return redirect()->back()->withInput()->withErrors('该用户已存在，请登录!');
            }

            $insert = Users::insert([
                'phone' => $phone,
                'password' => $password,
                'car_num' => $car_num,
            ]);
            if ($insert) {
                Session::put('phone', $phone);
                Session::put('car_num', $car_num);
                $list = Users::where('car_num',$car_num)->first()->toArray();
                Session::put('uid', $list['id']);
                Session::put('username', $list['username']);
                return Redirect::to('/')->withErrors('注册成功!');
            } else {
                return redirect()->back()->withInput()->withErrors('注册失败!');
            }
        } else {
            return redirect()->back()->withInput()->withErrors('验证码失效或错误!');
        }
    }

    //用户登录
    public function login()
    {
        $name = input::get('name');
        $password = md5(input::get('password'));
        $code = input::get('code');
        //exit();
        if (empty($name) || empty($password)) {
            return redirect()->back()->withInput()->withErrors('账号密码不能为空!');
        }
        if (empty($code)) {
            return redirect()->back()->withInput()->withErrors('验证码不能为空!');

        }
        if (Captcha::check($code) == true) {
            $list = Users::where([
                ['car_num', $name],
                ['password', $password],
            ])->first();
            if ($list) {

                if ($list['status'] == 1) {
                    // $getip = $this->getRealIp(); //获取IP地址
                    $ip = ip2long('127.0.0.1');
                    if ($ip != $list['ip']) { //判断登录IP是否与数据库IP地址相同，不同则更新数据库
                        $data['ip'] = $ip;
                    }
                    $number = Users::where('id', $list['id'])->increment('login_number');
                    $data['login_time'] = date("Y-m-d H:i:s");
                    $map = Users::where('id', $list['id'])->update($data);

                    Session::put('phone', $list['phone']);
                    Session::put('car_num', $list['car_num']);
                    Session::put('uid', $list['id']);
                    Session::put('username', $list['username']);
                    return Redirect::to('/')->withErrors('登录成功!');
                } else {
                    return redirect()->back()->withInput()->withErrors('账号已被禁用，请联系管理员!');
                }
            } else {
                return redirect()->back()->withInput()->withErrors('账号不存在，请先注册!');
            }
        } else {
            return redirect()->back()->withInput()->withErrors('验证码错误!');
        }
    }

    //加载重置密码页
    public function forgetPass() {
        return view('client.forgetPass');
    }

    //验证账号和手机号
    public function username() {
        $car_num = input::get('car_num');
        $phone = input::get('phone');
        $code = input::get('code');
        $v = Validate::where('phone', $phone)->first();
        if ($v && time() - strtotime($v->create_time) < 300 && $code == $v->code) {
            $list = Users::where('car_num',$car_num)->where('phone',$phone)->first()->toArray();
            dump($list);
            if($list) {
                return view('client.reset',['list'=>$list]);
            }
            else {
                return redirect()->back()->withErrors('用户不存在');
            }
        }
        else {
            return redirect()->back()->withInput()->withErrors('验证码错误或超时!');
        }
    }

    //重置密码
    public function reset() {
        $password = md5(input::get('password'));
        $d_pass = md5(input::get('d_password'));
        $id = input::get('uid');
        if($password == $d_pass) {
            $list = Users::where('id',$id)->update(['password'=>$password]);
            if($list) {
                return Redirect::to('client/toLogin')->withErrors('重置成功，请登录！');
            }
            else {
                return redirect()->back()->withInput()->withErrors('重置失败!');
            }
        }
        else {
            return redirect()->back()->withInput()->withErrors('两次密码输入不一致!');
        }
    }

//    //重置密码
//    public function rePassword() {
//        $phone = input::get('phone');
//        $password = md5(input::get('password'));
//        $d_password = md5(input::get('d_password'));
//        $code = input::get('code');
//
//        if(empty($code) || empty($password) || empty($d_password) || empty($phone)) {
//            return back()->withErrors('请填写完整信息!');
//        }
//        if($password != $d_password) {
//            return redirect()->back()->withInput()->withErrors('两次密码不一致！');
//        }
//        $v = Validate::where('phone',$phone)->first();
//        if($v && time() - strtotime($v->create_time) < 300 && $code == $v->code) {
//            $y = Users::where('phone',$phone)->first();
//            if($y) {
//                Users::where('phone',$phone)->update([
//                    'password' => $password
//                ]);
//                return Redirect::to('client/toLogin')->withErrors('重置成功!');
//            }
//            else {
//                return redirect()->back()->withInput()->withErrors('账号不存在，请先注册!');
//            }
//        }
//        else {
//            return redirect()->back()->withInput()->withErrors('验证码失效或错误!');
//        }
//    }

    //获取登录IP地址
    public function getReadIp() {
        $ip = false; // 初始化IP为false
        if(!empty($_SERVER["HTTP_CLIENT_IP"])) { //如果HTTP_CLIENT_IP 不为空
            $ip = $_SERVER["HTTP_CLIENT_IP"]; //获取HTTP_CLIENT_IP的值
        }
        if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //如果HTTP_X_FORWARDED_FOR不为空
            $ips = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']); //把HTTP_X_FORWARDED_FOR的值用,分割后存放数组ips
            if($ip) {
                array_unshift($ips,$ip);
                $ip = false; //遍历处理
            }
            for($i = 0;$i < count($ips);$i++) {
                if(!eregi("^(10|172.16|192.168).",$ips[$i])) {
                    $ip = $ips[$i]; //获取真实IP
                }
            }
        }
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

    //注销
    public function logout() {
        Session::put('phone',null);
        Session::put('username',null);
        Session::put('uid',null);
        return Redirect::to("");
    }
}